﻿using System;
using System.IO;
using System.Reflection;
using System.Text;

namespace ConsoleCommand.Commands
{
    class ExtractResourceCommand : ICommand
    {
        string assembly;
        string resource;

        public ExtractResourceCommand(string assembly,string resource){
            this.assembly=assembly;
            this.resource=resource;
        }

        public object Execute() {
            Assembly assembly=Assembly.LoadFrom(this.assembly);
            if(String.IsNullOrEmpty(resource))return GetAllResources(assembly);
            return GetResource(assembly, resource);
        }

        string GetAllResources(Assembly assembly) {
            string[] resourceList = assembly.GetManifestResourceNames();
            StringBuilder resources = new StringBuilder();
            foreach(string resource in resourceList){
                resources.Append(GetResource(assembly, resource));
            }
            return resources.ToString();
        }

        string GetResource(Assembly assembly,string resource){
            Stream resourceStream = assembly.GetManifestResourceStream(resource);
            if (resourceStream == null) throw new ArgumentException(String.Format("The resource '{0}' was not found in the assembly '{1}'.", resource, assembly.FullName));
            StreamReader reader=new StreamReader(resourceStream,Encoding.UTF8);
            if(reader.EndOfStream)return String.Empty;
            return reader.ReadToEnd();
        }
    }
}
